import cv2

def detect(filename):
    # 加载xml文件生成分类器
    save_path = 'C:/Users/shouw/Desktop/tmp/capturesou/'
    face_detector = cv2.CascadeClassifier('D:/facere/venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
    img = cv2.imread(save_path + filename)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)   #转换成灰度文件

    # scaleFactor:图像缩小的比例
    face_rects = face_detector.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=3)

    # 用矩形框出每张人脸
    for(x,y,w,h) in face_rects:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)  # 蓝色框（B=255，G=R=0）
    cv2.imshow('Face Detector',img)
    k = cv2.waitKey(0)
    if k == 27:
        cv2.destroyAllWindows()
    elif k == ord('s') or k == ord('S'):
        save_path = 'C:/Users/shouw/Desktop/tmp/imgdesou/'
        cv2.imwrite(save_path + 'face' + filename + '.jpg',img)
    cv2.destroyAllWindows()
detect('person1.jpg')